/**
 * Copyright &copy; 2012-2014 hongsuan.pplive All rights reserved.
 */
package com.hongsuan.pplive.modules.cms.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cnjson.db.persistence.Page;
import com.cnjson.db.service.CrudService;
import com.cnjson.common.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.cnjson.common.config.Global;
import com.hongsuan.pplive.modules.cms.dao.ArticleDao;
import com.hongsuan.pplive.modules.cms.dao.ArticleDataDao;
import com.hongsuan.pplive.modules.cms.dao.CategoryDao;
import com.hongsuan.pplive.modules.cms.entity.Article;
import com.hongsuan.pplive.modules.cms.entity.ArticleData;
import com.hongsuan.pplive.modules.cms.entity.Category;
import com.hongsuan.pplive.modules.sys.utils.UserUtils;

/**
 * 文章Service
 * @author ThinkGem
 * @version 2013-05-15
 */
@Service
@Transactional(readOnly = true)
public class ArticleService extends CrudService<ArticleDao, Article> {

	@Autowired
	private ArticleDataDao articleDataDao;
	@Autowired
	private CategoryDao categoryDao;
    @Autowired
    private ArticleSearchService articleSearchService;
    @Autowired
    private ArticleDao articleDao;


	@Transactional(readOnly = false)
	public Page<Article> findPage(Page<Article> page, Article article) {
//		DetachedCriteria dc = dao.createDetachedCriteria();
//		dc.createAlias("category", "category");
//		dc.createAlias("category.site", "category.site");
		if (article.getCategory()!=null && StringUtils.isNotBlank(article.getCategory().getId()) && !Category.isRoot(article.getCategory().getId())){
			Category category = categoryDao.get(article.getCategory().getId());
			if (category==null){
				category = new Category();
			}
			category.setParentIds(category.getId());
			article.setCategory(category);
		}
		else{
			article.setCategory(new Category());
		}
//		if (StringUtils.isBlank(page.getOrderBy())){
//			page.setOrderBy("a.weight,a.update_date desc");
//		}
//		return dao.find(page, dc);
		return super.findPage(page, article);

	}
	@Transactional(readOnly = false)
	public List<Article> findListFornt(Article article) {
		return articleDao.findListFornt(article);
	}
	@Transactional(readOnly = false)
	public Page<Article> findListForntPage(Page<Article> page, Article article) {
		article.setPage(page);
		page.setList(articleDao.findListFornt(article));
		return page;
	}
	@Transactional(readOnly = false)
	public void save(Article article) {
		if (article.getArticleData().getContent()!=null){
			article.getArticleData().setContent(StringEscapeUtils.unescapeHtml4(
					article.getArticleData().getContent()));
		}
		// 如果没有审核权限，则将当前内容改为待审核状态
		if (!UserUtils.getSubject().isPermitted("cms:article:audit")){
			article.setDelFlag(Article.DEL_FLAG_AUDIT);
		}
		// 如果栏目不需要审核，则将该内容设为发布状态
		if (article.getCategory()!=null&&StringUtils.isNotBlank(article.getCategory().getId())){
			Category category = categoryDao.get(article.getCategory().getId());
			if (!Global.YES.equals(category.getIsAudit())){
				article.setDelFlag(Article.DEL_FLAG_NORMAL);
			}
		}
		article.setUpdateBy(UserUtils.getUser().getId());
		article.setUpdateDate(new Date());

        ArticleData articleData = new ArticleData();
		if (StringUtils.isBlank(article.getId())){
			article.preInsert();
			articleData = article.getArticleData();
			articleData.setId(article.getId());
			dao.insert(article);
			articleDataDao.insert(articleData);
		}else{
			article.preUpdate();
			articleData = article.getArticleData();
			articleData.setId(article.getId());
			dao.update(article);
			articleDataDao.update(article.getArticleData());
		}

        articleSearchService.updateIndex(article);
	}

	@Transactional(readOnly = false)
	public void delete(Article article, Boolean isRe) {
//		dao.updateDelFlag(id, isRe!=null&&isRe?Article.DEL_FLAG_NORMAL:Article.DEL_FLAG_DELETE);
		// 使用下面方法，以便更新索引。
		//Article article = dao.get(id);
		//article.setDelFlag(isRe!=null&&isRe?Article.DEL_FLAG_NORMAL:Article.DEL_FLAG_DELETE);
		//dao.insert(article);
		super.delete(article);

        articleSearchService.deleteIndex(article);
	}

	/**
	 * 通过编号获取内容标题
	 * @return new Object[]{栏目Id,文章Id,文章标题}
	 */
	public List<Object[]> findByIds(String ids) {
		if(ids == null){
			return new ArrayList<Object[]>();
		}
		List<Object[]> list = Lists.newArrayList();
		String[] idss = StringUtils.split(ids,",");
		Article e = null;
		for(int i=0;(idss.length-i)>0;i++){
			e = dao.get(idss[i]);
			list.add(new Object[]{e.getCategory().getId(),e.getId(),StringUtils.abbr(e.getTitle(),50)});
		}
		return list;
	}

	/**
	 * 点击数加一
	 */
	@Transactional(readOnly = false)
	public void updateHitsAddOne(String id) {
		dao.updateHitsAddOne(id);
	}

	/**
	 * 更新索引
	 */
	public void createIndex(){
        Article article = new Article();
        article.setDelFlag(Article.DEL_FLAG_NORMAL);

		List<Article> allList = dao.findAllList(article);
        articleSearchService.createIndex(allList);
	}

	/**
	 * 全文检索
	 */
	public Page<Article> search(Page<Article> page, String q, String categoryId, String beginDate, String endDate){
        return articleSearchService.search(page,q,categoryId,beginDate,endDate);
	}
	
	public boolean checkHljToken(String artisan_id,String token)throws Exception{
		StringBuffer url = new StringBuffer("https://app.helijia.com/zmw/artisan/check_token");
		//url.append("?artisan_id=").append(artisan_id).append("&");
		//url.append("token=").append(token);
		HttpClient client = new HttpClient();
		client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
		PostMethod method = new PostMethod(url.toString());
		method.setParameter("artisan_id", artisan_id);
		method.setParameter("token", token);
		int code = client.executeMethod(method);
		if (code == 200) {
			String callBackString = method.getResponseBodyAsString();
			java.util.HashMap<String,Object> reportParamMap =  new ObjectMapper().readValue(callBackString, java.util.HashMap.class);
			boolean ret= (Boolean)reportParamMap.get("ret");
			String message= (String)reportParamMap.get("message");
			return ret;
		}
		return false;
	}
	
	
	public static void main(String[] args) {
		try {
			new ArticleService().checkHljToken("5cafd5966eb74a5e8b5352e5ec6a46b3", "SxjrXXadsomADlcg5B7H");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
